package com.oneraku.service.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.oneraku.service.domain.AgentBuy;
import com.oneraku.service.dao.AgentBuyMapper;
import com.oneraku.service.exceptions.InfoException;
import com.oneraku.service.service.IAgentBuyService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.oneraku.service.utils.AuthBean;
import com.oneraku.service.utils.R;
import com.oneraku.service.utils.RequestUserUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * <p>
 * 代购 服务实现类
 * </p>
 *
 * @author renhui <337375464@qq.com>
 * @since 2020-02-25
 */
@Service
public class AgentBuyServiceImpl extends ServiceImpl<AgentBuyMapper, AgentBuy> implements IAgentBuyService {
    private void checkBean(AgentBuy agentBuy){
        if(StringUtils.isEmpty(agentBuy.getUrl()) && agentBuy.getUrl().indexOf("http") != 0){
           throw new InfoException("购买链接不能为空");
        }
        if(StringUtils.isEmpty(agentBuy.getName())){
            throw new InfoException("购买名称不能为空");
        }
        if(StringUtils.isEmpty(agentBuy.getNum())){
            throw new InfoException("购买数量不能为空");
        }
    }
    @Override
    public R listAgentBuy(AgentBuy agentBuy) {
        AuthBean authBean = RequestUserUtils.getUser();
        return R.okPage(page(agentBuy.page(),Wrappers.<AgentBuy>lambdaQuery().eq(AgentBuy::getCreator,authBean.getId())));
    }

    @Override
    public R editAgentBuy(AgentBuy agentBuy) {
        String agentBuyId = agentBuy.getId();
        if(StringUtils.isEmpty(agentBuyId)){
            throw new InfoException("更新标识未知");
        }
        checkBean(agentBuy);
        AuthBean authBean = RequestUserUtils.getUser();
        agentBuy.setCreator(authBean.getId());
        return R.ok(save(agentBuy));
    }

    @Override
    public R delAgentBuy(AgentBuy agentBuy) {
        String agentBuyId = agentBuy.getId();
        if(StringUtils.isEmpty(agentBuyId)){
            throw new InfoException("删除标识未知");
        }
        AuthBean authBean = RequestUserUtils.getUser();
        AgentBuy localAgentBuy = getById(agentBuyId);
        if(null == localAgentBuy){
            throw new InfoException("未找到相关的代购订单");
        }
        if(!localAgentBuy.getCreator().equals(authBean.getId())){
            throw new InfoException("没有权限删除该代购订单");
        }
        return R.ok(removeById(localAgentBuy.getId()));
    }

    @Override
    public R addAgentBuy(AgentBuy agentBuy) {
        checkBean(agentBuy);
        agentBuy.setId(null);
        AuthBean authBean = RequestUserUtils.getUser();
        agentBuy.setCreator(authBean.getId());
        return R.ok(save(agentBuy));
    }
}
